/******************************************************************************
* FILE: hello.c
* DESCRIPTION:
*   A "hello world" Pthreads program.  Demonstrates thread creation and
*   termination.
* AUTHOR: Blaise Barney
* LAST REVISED: 08/09/11
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "integrate.h"

#define NUM_THREADS 5

typedef struct integrate_opt
{
    double start;
    double finish;
    double epsilon;
} integrate_opt;

void display_usage()
{
    printf("Please use -n option to specify thread count, like -n 2...\n");

}

void *integrate(void *opt)
{
    struct integrate_opt *options = (integrate_opt *)opt;
    double start = options->start;
    double finish = options->finish;
    double epsilon = options->epsilon;
    double *res = (double *)malloc(sizeof(double));
    *res = integrate_trap(start, finish, epsilon);
    pthread_exit( (void *)res);
}

int main(int argc, char *argv[])
{
    if (argc !=3){
      display_usage();
      return 0;
    }
    int opt = 0;
    int thread_count = 1;
    while ( opt != -1 )
    {
        switch ( opt )
        {
        case 'n':
            thread_count = atoi(optarg);
            break;


        case 'h':   /* намеренный проход в следующий case-блок */
        case '?':
            display_usage();
            break;

        default:
            /* сюда на самом деле попасть невозможно. */
            break;
        }

        opt = getopt( argc, argv, "n:" );
    }
    printf("thread count is : %d \n", thread_count);

    double *input = read_from_file();
    double start = input[0];
    double finish = input[1];
    double epsilon = input[2];
    double step = (finish - start) / thread_count;




    pthread_t threads[thread_count];
    double res = 0;
    int rc;
    long t;
    for (t = 0; t < thread_count; t++)
    {
        printf("In main: creating thread %ld\n", t);
        struct integrate_opt *opt = (integrate_opt *)malloc(sizeof(double) * 3);
        opt->start = start + t * step;
        opt->finish = start + (t + 1) * step;
        opt->epsilon = epsilon / thread_count;

        rc = pthread_create(&threads[t], NULL, integrate, (void *)opt);
    }

    for (t = 0; t < thread_count; t++)
    {
        void* current;
        pthread_join(threads[t], &current);
        res += *((double*)current);
    }

    /* Last thing that main() should do */
    printf("\n%lf\n", res);
    pthread_exit(NULL);

    //res = integrate_trap(input[0], input[1], input[2]);
    
    return 0;

}
